<?php
    class IP
    {
        function isValid($ip_addr)
        {
            $rr = array();
            if (!ereg('^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$', $ip_addr, $rr)) return false;
            
            return true
                && ($rr[1] >= 0) && ($rr[1] <= 255)
                && ($rr[2] >= 0) && ($rr[2] <= 255)
                && ($rr[3] >= 0) && ($rr[3] <= 255)
                && ($rr[4] >= 0) && ($rr[4] <= 255);
        }

        function dotToLongIP ($IPaddr)
        {
            if ($IPaddr == "")
            {
                return 0;
            }
            else
            {
                $ips = split ("\.", "$IPaddr");
                return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
            }
        }
        
        function longIPToDot($ip, $zero_padding = false)
        {
            $w = ( $ip / 16777216 ) % 256;
            $x = ( $ip / 65536    ) % 256;
            $y = ( $ip / 256      ) % 256;
            $z = ( $ip            ) % 256;
            
            if ($zero_padding)
                return sprintf("%03d.%03d.%03d.%03d", $w,$x,$y,$z);
            else
                return "$w.$x.$y.$z";
        }
        
        function getDotIP()
        {
           if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
                   $ip = getenv("HTTP_CLIENT_IP");
               else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                   $ip = getenv("HTTP_X_FORWARDED_FOR");
               else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                   $ip = getenv("REMOTE_ADDR");
               else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                   $ip = $_SERVER['REMOTE_ADDR'];
               else
                   $ip = "";
           return($ip);
        }

        function getIP()
        {
            return IP::dotToLongIP( IP::getDotIP() );
        }
    }

?>
